/* $Id:material.cc $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "material"

#include <sstream>
#include <fstream>
#include "../general/util.h"
#include "../general/log.h"
#include "../general/channel.h"
#include "material.h"
#include "item.h"
#include "../general/general.h"

material::material() {
    item=0;
    amount=0;
    position=0;
}

// Field : item

class item& material::getItem() const { if (item==0) throw nullpointer(); return *item; }
void material::setItem(class item &v) { item=&v; }

// Field : amount

const int material::getAmount() const { return amount; }
void material::setAmount(const int v) { amount=v; }

// Field : position

const int material::getPosition() const { return position; }
void material::setPosition(const int  v) { position=v; }
const string material::showPosition() const {
    stringstream res;
    res << "(" << (position & 0xffff) << "," << (position << 16) << ")";
    return res.str();
}
int material::operator<(const class material &ck) const {
    return (getItem().getNr() < ck.getItem().getNr())?1:0;
}

void material::save(class channel &ch) {
    ch.write("material", "");
    ch.write("i", getItem().getName());
    ch.write("a", getAmount());
    ch.write("p", getPosition());
}

void material::load(class channel &ch) {
    if (ch.key=="i" || ch.key=="item") {
        if (!item_repo.isItem(ch.value)) {
            dbg_state("link unknown item %s", ch.value.c_str());
            class item rec;
            rec.setName(ch.value);
            item_repo.setItem(rec);
            rec.setNr(0);
        }
        setItem(item_repo.getItem(ch.value));
        ch.next();
    }
    if (ch.key=="a" || ch.key=="amount") { setAmount(atoi(ch.value.c_str())); ch.next(); }
    if (ch.key=="p" || ch.key=="position") { setPosition(atoi(ch.value.c_str())); ch.next(); }
}

void material::xml(ofstream &f, int l, int r) {
    f << ncpy(l, "  ") << "<material amount=\"" << getAmount() <<
    "\" position_x=\"" << (getPosition() & 0xffff) <<
    "\" position_y=\"" << (getPosition() << 16) <<
    "\">" << endl;
    if (r<2) try {
        getItem().xml(f,l+1,r+1);
    } catch (nullpointer n) {}
    f << ncpy(l, "  ") << "</material>" << endl;
}
